<!--
 * @author  guojiteng
 投票活动-投票结果
-->
<template>
  <section class="result-main">
    <section class="main-buttons">
      <section class="main-buttons-title">
        <span>投票结果：</span>
        <span>
          一共投票次数为
          <span class="num">{{ ps }}</span> 人数为
          <span class="num">{{ rs }}</span>
        </span>
      </section>
      <section class="main-buttons-btns" />
      <!-- <el-button style="margin-left: 10px" @click="handleExport"
        >批量导出</el-button
      >-->
      <el-button @click="handleExport">导出</el-button>
      <el-button @click="activeTab === '1' ? getList() : getList4Detail()">刷新</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="back()">返回</el-button>
    </section>
    <div class="classify-tab">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="票数统计" name="1" />
        <el-tab-pane label="票数明细" name="2" />
      </el-tabs>
    </div>
    <section v-show="activeTab === '2'" class="main-search separate">
      <section class="search-inner">
        <el-row>
          <el-col :span="12">
            <section class="search-inner-item">
              <div class="item-label">姓名</div>
              <el-input
                v-model.trim="listQuery4Detail.userName"
                style="width: 90%;"
                class="filter-item"
                placeholder="请输入姓名搜索"
              />
            </section>
          </el-col>
          <el-col :span="12">
            <section class="search-inner-item">
              <div class="item-label">投票项</div>
              <el-select v-model="listQuery4Detail.candidateIds" style="width: 90%;" placeholder="请选择">
                <el-option v-for="(item, index) in list" :key="index" :label="item.mainTitle" :value="item.id" />
              </el-select>
            </section>
          </el-col>
        </el-row>
      </section>
      <section class="search-btn">
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button type="primary" @click="handleReset">重置</el-button>
      </section>
    </section>
    <section class="main-table">
      <template v-if="activeTab === '1'">
        <v-table
          :list="list"
          tag="voteResult"
          :source-arr="['img']"
          :list-loading="listLoading"
          :filter-column="filtercolumn"
        >
          <el-table-column
            v-if="activeTab === '1'"
            label="操作"
            fixed="right"
            align="center"
            min-width="120"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                type="text"
                size="mini"
                @click="handleAdd(scope.row.id)"
              >增加票数</el-button>
            </template>
          </el-table-column>
        </v-table>
      </template>
      <template v-else>
        <v-table
          :list="list4Detail"
          tag="voteResult4Detail"
          :source-arr="['img']"
          :list-loading="listLoading"
          :filter-column="filtercolumn"
        />
        <pagination
          v-show="activeTab === '2' && total4Detail>0"
          :total="total4Detail"
          :page.sync="listQuery4Detail.page"
          :limit.sync="listQuery4Detail.limit"
          @pagination="getList4Detail"
        />
      </template>

    </section>
  </section>
</template>
<script>
import VTable from '@/components/Table'
import { queryResult, queryResult4Detail, exportFile, ticketDetailExportFileNoMask, ticketDetailExportFileMask } from '../api/index'
import permission from '@/directive/permission/index.js'
import { addPacket } from '@/views/activity/tphd/api/option'
import Pagination from '@/components/Pagination'
import { exportSign } from '@/utils/fileImportOrExportSign'
import { exportCheck } from '@/utils/sensitiveInfoExportCheck'
import CryptoJS from '@/utils/aes'
export default {
  name: 'Resultindex',
  components: { VTable, Pagination },
  directives: { permission },
  data() {
    return {
      listQuery4Detail: {
        page: 1,
        limit: 10,
        userName: '',
        candidateIds: ''
      },
      total4Detail: 0,
      list: [],
      list4Detail: [],
      listLoading: false,
      id: '',
      view: '/API-DOCUMENT/document/file/download?id=',
      ps: 0,
      rs: 0,
      activeTab: '1'
    }
  },
  created() {
    if (this.$route.query.i) {
      this.id = this.$route.query.i
      this.getList()
    } else {
      this.$message.error('参数错误')
      this.$router.back()
    }
  },
  methods: {
    /**
     * 选项卡切换
     */
    handleTabClick(tab, event) {
      if (this.activeTab === '1') {
        this.getList()
      } else {
        this.getList4Detail()
      }
    },
    /**
     * 增加票数
     */
    handleAdd(id) {
      this.$prompt('请输入要增加的票数', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'Number',
        inputValidator: (val) => {
          const reg = /^\+?[1-9][0-9]*$/
          if (reg.test(val)) {
            if (+val > 10000) {
              return '增加票数不得大于10000'
            } else {
              return true
            }
          } else {
            return '请填写非零正整数'
          }
        }
      }).then(({ value }) => {
        return new Promise((resolve, reject) => {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          addPacket({ dataId: this.$route.query.i, candidateId: id, number: value }).then((res) => {
            loading.close()
            this.$alert(res.data.data, '操作成功', {
              confirmButtonText: '确定'
            })
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      })
    },
    filtercolumn(scope, item) {
      if (item === 'img') {
        return `${this.view + scope.row['coverImgId']}`
      } else if (item === 'phoneNumber' || item === 'userIdnumber') {
        return CryptoJS.$aesJieM(scope.row[item])
      } else {
        return scope.row[item]
      }
    },
    back() {
      this.$router.back()
    },
    getList() {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryResult({ id: this.id }).then(response => {
          this.list = response.data.data.votingCandidate
          this.rs = response.data.data.countPeople
          this.ps = response.data.data.countTotal
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    getList4Detail(obj) {
      this.listLoading = true
      return new Promise((resolve, reject) => {
        const query = {
          dataId: this.id,
          page: obj ? obj.page : this.listQuery4Detail.page,
          pageSize: obj ? obj.limit : this.listQuery4Detail.limit,
          userName: this.listQuery4Detail.userName,
          candidateIds: this.listQuery4Detail.candidateIds
        }
        queryResult4Detail(query).then(response => {
          this.list4Detail = response.data.data.rows
          this.total4Detail = response.data.data.total
          this.listLoading = false
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },
    handleReset() {
      this.listQuery4Detail.page = 1
      this.listQuery4Detail.userName = ''
      this.listQuery4Detail.candidateIds = ''
      this.getList4Detail()
    },
    handleFilter() {
      this.listQuery4Detail.page = 1
      this.getList4Detail()
    },
    handleExport() {
      if (this.activeTab === '1') {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        const query = exportSign({
          id: this.id
        }).obj
        exportFile(query).then((res) => {
          loading.close()
          const content = res.data
          const blob = new Blob([content])
          const fileName = '票数统计.xlsx'
          if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
          } else {
            navigator.msSaveBlob(blob, fileName)
          }
        }).catch(() => {
        // this.$message.error()
          loading.close()
        })
      } else if (this.activeTab === '2') {
        const query = exportSign({
          dataId: this.id,
          userName: this.listQuery4Detail.userName,
          candidateIds: this.listQuery4Detail.candidateIds
        }).obj
        exportCheck('STAFF_SERVICE_POLLING', this.id, ticketDetailExportFileMask, ticketDetailExportFileNoMask, query, '票数明细.xlsx')
        return
        // ticketDetailExportFile(query).then((res) => {
        //   loading.close()
        //   const content = res.data
        //   const blob = new Blob([content])
        //   const fileName = '票数明细.xlsx'
        //   if ('download' in document.createElement('a')) {
        //     const elink = document.createElement('a')
        //     elink.download = fileName
        //     elink.style.display = 'none'
        //     elink.href = URL.createObjectURL(blob)
        //     document.body.appendChild(elink)
        //     elink.click()
        //     URL.revokeObjectURL(elink.href) // 释放URL 对象
        //     document.body.removeChild(elink)
        //   } else {
        //     navigator.msSaveBlob(blob, fileName)
        //   }
        // }).catch(() => {
        // // this.$message.error()
        //   loading.close()
        // })
      }
    }
  }
}
</script>
<style lang="scss">

.result-main {
  padding: 10px;

  .main-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: #bfced6;
      vertical-align: middle;
      display: inline-block;
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            &.el-date-editor input {
              padding-left: 30px;
            }

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .classify-tab {
    width: 100%;
    margin: 10px 0;
    padding: 0 10px;
    background-color: #fff;
    display: flex;
    border-radius: 4px;

    .el-tabs__nav-wrap::after {
      display: none;
    }

    .el-tabs__header {
      margin: 0;
    }
  }

  .main-buttons {
    display: flex;
    line-height: 36px;
    margin-top: 10px;

    .main-buttons-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      font-weight: bold;
      color: rgba(51, 51, 51, 1);

      .num {
        @include font-color($mainColor);
      }
    }
  }
}
</style>
